#!/usr/bin/python3
# -*- coding: utf-8 -*-

import time
import threading


class MyTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer = None
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = threading.Timer(self.interval, self._run)
            self._timer.daemon = True
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

    def __del__(self):
        print('Timer __del__ call')
        self.stop()


class ThreadTimer(threading.Thread):
    def __init__(self, interval=None, function=None, *args, **kwargs):
        threading.Thread.__init__(self)
        self.daemon = True
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.event = threading.Event()

    def run(self):
        call_time = time.time()
        next_time = call_time
        while not self.event.is_set():
            next_time = next_time + self.interval
            if next_time - call_time > 0: time.sleep(next_time - call_time)
            if self.function is not None:
                self.function(*self.args, **self.kwargs)
            call_time = time.time()

    def stop(self):
        self.event.set()

    def __del__(self):
        self.event.set()
